package com.acoreful.acf2java.commons.security;

import java.security.Key;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AesUtils {
    
    private static final Logger logger = LoggerFactory.getLogger(AesUtils.class);

    public static String aesEncrypt(String strToEncrypt, String key) {
        if (StringUtils.isEmpty(strToEncrypt) || StringUtils.isEmpty(key)) {
            return "";
        }
        
        Key keySpec = new SecretKeySpec(key.getBytes(), "AES");
        try {
            Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
            c.init(Cipher.ENCRYPT_MODE, keySpec);
            return Base64.getEncoder().encodeToString(c.doFinal(strToEncrypt.getBytes()));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return "";
        }
    }
    
    public static String aesDecrypt(String encryptedStr, String key) {
        if (StringUtils.isEmpty(encryptedStr) || StringUtils.isEmpty(key)) {
            return "";
        }
        
        Key keySpec = new SecretKeySpec(key.getBytes(), "AES");
        try {
            Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding");
            c.init(Cipher.DECRYPT_MODE, keySpec);
            return new String(c.doFinal(Base64.getDecoder().decode(encryptedStr.getBytes())));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return "";
        }
    }

    
}
